package net.liteheaven.xblib.widget.grid;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.GridView;

import java.lang.reflect.Field;

/**
 * 可定高GridView
 *
 * 特性：可定高、可获取列宽
 *
 * Created by LiangYu on 16/8/29
 */
public class FixedGridView extends GridView{
    private boolean autoMeasure = true;
    public FixedGridView(Context context){
        super(context);
        init();
    }

    public FixedGridView(Context context, AttributeSet attrs){
        super(context, attrs);
        init();
    }

    public FixedGridView(Context context, AttributeSet attrs, int defStyle){
        super(context, attrs, defStyle);
        init();
    }

    private void init(){
        setSelector(new ColorDrawable(Color.TRANSPARENT));
    }

    public void disableAutoMeasure(){
        autoMeasure = false;
        requestLayout();
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (autoMeasure){
            int expandSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                    View.MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);
        }else{
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    @SuppressLint("NewApi")
    @Override
    public int getColumnWidth(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return super.getColumnWidth();
        else{
            try{
                Field field = GridView.class.getDeclaredField("mColumnWidth");
                field.setAccessible(true);
                Integer value = (Integer) field.get(this);
                field.setAccessible(false);
                return value.intValue();
            }catch(NoSuchFieldException e){
                throw new RuntimeException(e);
            }catch(IllegalAccessException e){
                throw new RuntimeException(e);
            }
        }
    }
}
